package com.huangsm.book.designmodel.key;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author huang
 * @PACKAGE_NAME com.huangsm.book.designmodel.key
 * @PROJECT_NAME concurrence
 * @date 2019/2/20
 */
public class ReentrantLockDemo {
     static final ReentrantLock lock=new ReentrantLock();
    private static Runnable craeteTask(){
        return new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        if (lock.tryLock(500, TimeUnit.SECONDS)) {
                            try {
                                System.out.println("locked" + Thread.currentThread().getName());
                                Thread.sleep(1000);
                            } finally {
                                lock.unlock();
                                System.out.println("unlocked" + Thread.currentThread().getName());
                            }
                            break;
                        } else {
                            System.out.println("unable to lock " + Thread.currentThread().getName());
                        }
                    } catch (InterruptedException e) {
                        System.out.println(Thread.currentThread().getName());
                    }
                }
            }
        };
    }

    public static void main(String[] args) throws InterruptedException {
        Thread firstThread = new Thread(craeteTask(), "FirstThread");
        Thread secondThread = new Thread(craeteTask(), "secondThread");
        firstThread.start();
        secondThread.start();
        Thread.sleep(600);
        //中断
        secondThread.interrupt();

    }
}
